package com.dlgcy.weibo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 获取配置文件
 * 
 * @author liqiang
 * 
 */
public class ConfigUtil {
	public static String FILE_PATH = "qqconnect.properties";  //配置文件路径；
	private static Properties propertie = new Properties();
	private static FileInputStream inputFile;
	private static FileOutputStream outputFile;
	
	public static void start() {
		try {
			inputFile = new FileInputStream(FILE_PATH);
			propertie.load(inputFile);
			inputFile.close();
		} catch (FileNotFoundException ex) {
			System.out.println("读取属性文件--->失败！- 原因：文件路径错误或者文件不存在");
			ex.printStackTrace();
		} catch (IOException ex) {
			System.out.println("装载属性文件--->失败!");
			ex.printStackTrace();
		}
	}

	public static String getValue(String key) {
		start();
		if (propertie.containsKey(key)) {
			String value = propertie.getProperty(key);// 得到某一属性的值
			return value;
		} else
			return "";
	}// end getValue()

	public static int getIntValue(String key) {
		String value = getValue(key);

		if (value != "") {
			return Integer.parseInt(value);
		}

		return 0;
	}

	public static void setValue(String key, String value) {
		start();
		propertie.setProperty(key, value);
	}// end setValue()

	/** */
	/**
	 * 将更改后的文件数据存入指定的文件中，该文件可以事先不存在。
	 * 
	 * @param fileName
	 *            文件路径+文件名称
	 * @param description
	 *            对该文件的描述
	 */
	public static void saveFile(String fileName, String description) {
		try {
			outputFile = new FileOutputStream(fileName);
			propertie.store(outputFile, description);
			outputFile.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}// end saveFile()

	public static void setValueAndSave(String key, String value, String fileName) {
		setValue(key, value);
		saveFile(fileName, null);
	}
	
	public static boolean deleteKeyValue4Pro(String delete_key, String delete_value, String filePath) {
		boolean flag = false;
		String toreplace =delete_key + "=" + delete_value + "\n";
		try {
			StringBuffer sb = new StringBuffer();
			String templine;
			File file = new File(filePath);
			BufferedReader bin = new BufferedReader(new FileReader(file));
			while ((templine = bin.readLine()) != null) {
				templine = unicodeToString(templine);
				sb.append(templine + "\n");
			}
			String save = new String(sb.toString());
			System.out.println("before delete:\n" + save + "\n--------------\n");
			System.out.println("delete:" + toreplace + "\n--------------\n");
			Pattern pattern = Pattern.compile(toreplace, Pattern.MULTILINE);
			Matcher matcher = pattern.matcher(save);
			while (matcher.find()) {
				save = matcher.replaceAll("");
			}
			/*
			 * 写回，我想字符串save里既然包含了换行，应该可以直接写回吧；
			 * 抱着试试看的心理，没想到可以用；（对于上面的代码不明觉历）；
			 */
			FileOutputStream output=new FileOutputStream(file);
			byte [] buff=new byte[]{};
            buff=save.getBytes();
            output.write(buff, 0, buff.length);
            output.close();
			
			/*网上的写回过程是这样的，总是报错（好像是空指针异常），然后配置文件都被清空了（因为没有写回）；
			BufferedWriter writer = new BufferedWriter(new FileWriter(file));
			String[] saves = save.split("\n");
			for (int i = 0; i < saves.length; i++) {
				String[] key_values = saves[i].split("=");
				writer.write(stringToUnicode((key_values[0]) + "=" + key_values[1] + "\n"));
			}
			System.out.println("after delete:\n" + save);
			writer.flush();
			bin.close();
			writer.close();*/
			flag = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return flag;
	}
	
	/** 
	 * 将字符串转成unicode 
	 * @param str 待转字符串 
	 * @return unicode字符串 
	 */ 
	public static String stringToUnicode(String str) 
	{ 
		str = (str == null ? "" : str); 
		String tmp; 
		StringBuffer sb = new StringBuffer(1000); 
		char c; 
		int i, j; 
		sb.setLength(0); 
		for (i = 0; i < str.length(); i++) 
		{ 
			c = str.charAt(i); 
			sb.append("\\u"); 
			j = (c >>>8); //取出高8位 
			tmp = Integer.toHexString(j); 
			if (tmp.length() == 1) 
				sb.append("0"); 
			sb.append(tmp); 
			j = (c & 0xFF); //取出低8位 
			tmp = Integer.toHexString(j); 
			if (tmp.length() == 1) 
				sb.append("0"); 
			sb.append(tmp); 
		} 
		return (new String(sb)); 
	} 
	
	/** 
	 * 将unicode 字符串 
	 * @param str 待转字符串 
	 * @return 普通字符串 
	 */ 
	public static String unicodeToString(String str) 
	{ 
		str = (str == null ? "" : str); 
		if (str.indexOf("\\u") == -1)//如果不是unicode码则原样返回 
			return str; 

		StringBuffer sb = new StringBuffer(1000); 

		for (int i = 0; i < str.length() - 6;) 
		{ 
			String strTemp = str.substring(i, i + 6); 
			String value = strTemp.substring(2); 
			int c = 0; 
			for (int j = 0; j < value.length(); j++) 
			{ 
				char tempChar = value.charAt(j); 
				int t = 0; 
				switch (tempChar) 
				{ 
				case 'a': 
					t = 10; 
					break; 
				case 'b': 
					t = 11; 
					break; 
				case 'c': 
					t = 12; 
					break; 
				case 'd': 
					t = 13; 
					break; 
				case 'e': 
					t = 14; 
					break; 
				case 'f': 
					t = 15; 
					break; 
				default: 
					t = tempChar - 48; 
					break; 
				} 

				c += t * ((int) Math.pow(16, (value.length() - j - 1))); 
			} 
			sb.append((char) c); 
			i = i + 6; 
		} 
		return sb.toString(); 
	}


}
